package cn.stylefeng.guns.modular.api;

import cn.stylefeng.guns.alipay.AliPayApi;
import cn.stylefeng.guns.core.PayModeType;
import cn.stylefeng.guns.modular.business.service.UserGradeService;
import cn.stylefeng.guns.sys.core.util.StringUtils;
import cn.stylefeng.guns.wxpay.kit.WxPayKit;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import cn.stylefeng.guns.pay.entity.AliPayBean;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by pzp on 2019/7/24.
 */
@Controller
@RequestMapping("/gunsApi/pay")
@Slf4j
public class PayApi extends BaseController{

    @Autowired
    private AliPayBean aliPayBean;

    @Autowired
    private UserGradeService userGradeService;

    @ApiOperation("支付宝升级之后的回调")
    @RequestMapping("/up-zfb-notify")
    @ResponseBody
    public String zfbNotify(HttpServletRequest request){
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);
            log.info("支付宝回调参数：" + JSONObject.toJSONString(params));
            boolean verify_result = AlipaySignature.rsaCheckV1(params, aliPayBean.getPublicKey(), "UTF-8",
                    "RSA2");
            // TODO 需要用消息队列去完成此步骤，此处暂时先这样处理
            if (verify_result) {// 验签成功
                String payCode = params.get("trade_status");
                if (payCode.equals("TRADE_SUCCESS")) {//支付成功
                    boolean result = userGradeService.toUpGrade(params, PayModeType.ALIPAY.getCode());
                    if(result) {
                        log.info("支付宝回调success:" + JSONObject.toJSONString(params));
                        return "success";
                    } else {
                        return "failure";
                    }
                }
            } else {
                log.info("notify_url 验证失败");
                // TODO
                return "failure";
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return "failure";
        }
        return "failure";
    }

    @ApiOperation("微信升级之后的回调")
    @PostMapping("/up-wx-notify")
    public String wxNotify(HttpServletRequest request, HttpServletResponse response){
        log.info("【微信回调开始】");
        BufferedReader in = null;
        String result = "";
        try {
            in = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        Map<String, String> resMp = WxPayKit.xmlToMap(result);
        log.info("微信回调参数：" + JSONObject.toJSONString(resMp));
        String resultOk = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        String result_code =  resMp.get("result_code");
        String return_code =  resMp.get("return_code");
        //支付成功再来调业务
        if (return_code.equals("SUCCESS") && result_code.equals("SUCCESS")) {
            String out_trade_no = resMp.get("out_trade_no");
            String trade_no = resMp.get("transaction_id");
            String total_fee = resMp.get("total_fee");
            if (StringUtils.isAnyEmpty(out_trade_no, trade_no, total_fee)) {
                return "fail";
            }
            BigDecimal totalFee = new BigDecimal(total_fee);
            totalFee = totalFee.divide(new BigDecimal("" + 100)).setScale(2, BigDecimal.ROUND_HALF_UP);
            //重装业务需要的参数
            Map<String, String> param = new HashMap<>();
            param.put("out_trade_no",  out_trade_no);
            param.put("trade_no", trade_no);
            param.put("total_amount", totalFee.toString());
            boolean resultB = userGradeService.toUpGrade(param, PayModeType.WECHAT.getCode());
            log.info("【微信回调业务处理结束：】" + resultB);
            if (resultB) {
                response.setContentType("application/xml; charset=utf-8");
                PrintWriter out = null;
                try {
                    out = response.getWriter();
                    out.print(resultOk);
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return "SUCCESS";
            }
        }
        return "fail";
    }
}
